package com.lee.dhsg.controller;

import com.lee.dhsg.domain.Teacher;
import com.lee.dhsg.service.TeacherService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

/**
 * 该控制器与教师有关
 * 1、教师登录
 * 2、教师注册
 * 3、退出登录
 * 4、
 *
 * @author Lee
 */

@Controller
public class TeacherController {

    @Autowired
    private TeacherService teacherService;

    /**
     * 教师登录
     */
    @RequestMapping("/teacherLogin")
    // @ResponseBody //这一个注释的作用：返回字符串直接显示，而不是作为路径
    public String teacherLogin(String username, String password, HttpSession session, Model model) throws Exception {
        if (password == null || username == null || username.equals("") || password.equals("")) {
            // 当表单数据为空时，登录失败
            return "";
        }
        Teacher teacher = teacherService.login(username, password); // 查询数据库中是否有该教师
        if (teacher != null) {
            // 登录成功

            session.setAttribute("TeacherSession", teacher);

            // todo...

            return "teacherIndex";
        } else {
            // 登录失败
            return "";
        }

    }

    /**
     * 退出登录
     */
    @RequestMapping("/teacherLogout")
    public String teacherLogout(HttpSession session) {
        // 清除保存 StudentSession 的 session
        session.removeAttribute("TeacherSession");
        return "redirect:index";
    }

    /**
     * 教师注册
     */
    @RequestMapping("/teacherRegister")
    public String teacherRegister(String username, String password) throws Exception {
        if (password == null || username == null || username.equals("") || password.equals("")) {
            // 当表单数据为空时，注册失败
            return "redirect:index";
        }
        teacherService.register(username, password); // 注册

        // 注册成功后完成登录
        String url = "redirect:teacherLogin？&username=" + username + "&password=" + password;
        return url;
    }

}
